from random import *


from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from celery_tasks.sms.tasks import send_sms_code
from libs.captcha.captcha import captcha
from untils.smsutils import SmsUtil


class ImageCodeView(View):
    def get(self, request, uuid):
        # 包 创建验证图标
        # text, image = captcha.generate_captcha()
        # # 传入redis中为接下来手动输入的进行比较
        # redis = get_redis_connection('code')
        # redis.setex(uuid, 300, text)
        # print(text,'text')
        # return HttpResponse(image, content_type='image/jpeg')
        text, image = captcha.generate_captcha()
        redis = get_redis_connection('code')
        redis.setex(uuid,300,text)
        return HttpResponse(image,content_type="image/jpeg")


class SmsView(View):
    def get(self, request, mobile):
        if not mobile:
            return JsonResponse({'code': 202, "errmsg": "号码不能为空"})
        redis = get_redis_connection('code')
        # 用户返回的验证码信息
        image_code = request.GET.get('image_code')
        # 单独的uuid
        try:
            uuid = request.GET.get('image_code_id')
            image_code_reids = redis.get(uuid)
            if image_code_reids is None:
                return JsonResponse({'code': 500, "errmsg": "数据错误"})
            image_code_reids = image_code_reids.decode()
            if image_code.lower() != image_code_reids.lower():
                return JsonResponse({'code': 100, "errmsg": "验证码与输入的验证码不对"})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 102, "errmsg": "数据不准确"})
        sms_code = '%06d' % randint(0, 999999)
        # 同步的
        # SmsUtil().send_message(mobile=mobile, code=sms_code)
        send_sms_code.delay(mobile,sms_code)
        print(sms_code)
        redis.setex('sms_code%s' % mobile,60*3,sms_code)
        return JsonResponse({'code': 0, "errmsg": "数据完成"})
